package cn.itcast.hello;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;

/**
 * @author KTL
 * @version V1.0
 * @Package cn.itcast.hello
 * @date 2021/2/21 0021 10:31
 * @Copyright © 2015-04-29  One for each, and two for each
 *      演示：flink-datastream-api-实现wordcount
 *      注意：lamen表达式写法
 */
public class WordCount4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        StreamExecutionEnvironment eMode = env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        DataStream<String> lines = env.fromElements("itcast hadoop spark", "itcast hadoop spark", "itcast hadoop", "itcast");
        /*
        public interface FlatMapFunction<T, O> extends Function, Serializable {
            void flatMap(T value, Collector<O> out) throws Exception;
        }
        */
        DataStream<String> words = lines.flatMap((String value, Collector<String> out) -> Arrays.stream(value.split(" ")).forEach(out::collect)).returns(Types.STRING);
        /*
        public interface MapFunction<T, O> extends Function, Serializable {
            O map(T value) throws Exception;
        */
        DataStream<Tuple2<String, Integer>> wordAndOne = words.map((String value) -> Tuple2.of(value, 1)).returns(Types.TUPLE(Types.STRING, Types.INT));
        KeyedStream<Tuple2<String, Integer>, String> grouped = wordAndOne.keyBy(key -> key.f0);
        final SingleOutputStreamOperator<Tuple2<String, Integer>> result = grouped.sum(1);
        result.print();
        env.execute();
    }
}
